<%--
  User: WGSpring
  Date: 2018/9/26
  Time: 11:26
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>

<head>
    <meta charset="UTF-8">
    <title>上传照片</title>
    <style type="text/css">
        .float {
            float: left;
            width: 200px;
            height: 200px;
            overflow: hidden;
            border: 1px solid #CCCCCC;
            border-radius: 10px;
            padding: 5px;
            margin: 5px;
        }

        img {
            position: relative;
        }

        .result {
            width: 200px;
            height: 200px;
            text-align: center;
            box-sizing: border-box;
        }

        #file_input {
            display: none;
        }

        .delete {
            width: 200px;
            height: 200px;
            position: absolute;
            text-align: center;
            line-height: 200px;
            z-index: 10;
            font-size: 30px;
            background-color: rgba(255, 255, 255, 0.8);
            color: #777;
            opacity: 0;
            transition-duration: 0.7s;
            -webkit-transition-duration: 0.7s;
        }

        .delete:hover {
            cursor: pointer;
            opacity: 1;
        }

        /*进度条相关*/
        .process-div {
            visibility: hidden;
            flex-direction: column;
            align-items: center;
        }

        .container2 {
            display: inline-block;
            width: 50%;
            height: 20px;
            padding-right: 10px;
            border: 1px solid #999;
            border-radius: 5px;
        }

        .h-100P {
            height: 100%;
        }

        .bar {
            display: inline-block;
            background: #90bf46;
            color: white;
            font-weight: bold;
            padding: 0 5px;
            text-align: right;
            border-radius: 5px;
            border-right: 1px solid #999;
        }


    </style>
    <link href="../../css/bootstrap.css" rel="stylesheet">
    <script src="../../js/jquery.js"></script>
    <script type="text/javascript">

        window.onload = function () {
            var input = document.getElementById("file_input");
            var fd = new FormData();  //FormData方式发送请求
            var index = 0;  //上传文件的编号
            var oSelect = document.getElementById("select");
            var oAdd = document.getElementById("add");
            var oSubmit = document.getElementById("submit");
            var oInput = document.getElementById("file_input");

            input.addEventListener('change', readFile, false);

            function readFile() {

                for (var i = 0; i < this.files.length; i++) {
                    if (!input['value'].match(/.jpg|.gif|.png|.jpeg|.bmp/i)) {　　//判断上传文件格式
                        return alert("上传的图片格式不正确，请重新选择");
                    }
                    fd.append("file" + index, this.files[i]);

                    var result = '<div class="delete">delete</div><div class="result"><img src="' + (window.URL || window.webkitURL).createObjectURL(this.files[i]) + '"/></div>';
                    var div = document.createElement('div');
                    div.innerHTML = result;
                    div['className'] = 'float';
                    div['index'] = "file" + index;
                    document.getElementsByTagName('body')[0].appendChild(div);  　　//插入dom树
                    var img = div.getElementsByTagName('img')[0];
                    img.onload = function () {
                        var nowHeight = ReSizePic(this); //设置图片大小
                        this.parentNode.style.display = 'block';
                        var oParent = this.parentNode;
                        if (nowHeight) {
                            oParent.style.paddingTop = (oParent.offsetHeight - nowHeight) / 2 + 'px';
                        }
                    };

                    div.onclick = function () {
                        this.remove();                  // 在页面中删除该图片元素
                        fd.delete(this.index);          // 删除fd对应的数据
                    };
                    index++;
                }
            }


            function send() {
                $(".process-div").css("visibility","visible");
                $.ajax({
                    url: '/upload-commit',
                    type: 'post',
                    async: true,
                    data: fd,
                    // dataType: 'json',
                    processData: false,   //用FormData传fd时需有这两项
                    contentType: false,
                    xhr: function () {
                        var myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) { // check if upload property exists
                            myXhr.upload.addEventListener('progress', function (e) {
                                var loaded = e.loaded;                  //已经上传大小情况
                                var total = e.total;                      //附件总大小
                                var percent = Math.floor(100 * loaded / total) + "%";     //已经上传的百分比
                                console.log("已经上传了：" + percent);
                                // $("#processBar").css("width", percent);

                                $('#progressBar').css('width', percent).text(percent);

                            }, false); // for handling the progress of the upload
                        }
                        return myXhr;
                    },
                    success: function () {
                        alert("上传成功");
                        window.location.href = "/index";
                    },
                    error: function () {
                        alert("上传失败！");
                    }

                })
            }


            oSelect.onclick = function () {
                oInput.value = "";   // 先将oInput值清空，否则选择图片与上次相同时change事件不会触发
                //清空已选图片
                $('.float').remove();
                fd = new FormData();
                index = 0;
                oInput.click();
            };


            oAdd.onclick = function () {
                oInput.value = "";   // 先将oInput值清空，否则选择图片与上次相同时change事件不会触发
                oInput.click();
            };


            oSubmit.onclick = function () {

                var iter = fd.entries();
                for (var item = iter.next(); item.value !== undefined; item = iter.next()) {
                    console.log('提交的文件数据：' + item.value[0] + " " + item.value[1].name);
                }

                if (fd.entries().next().value === undefined) {
                    return alert('请先选择文件');
                }

                send();
            }
        };

        /*
         用ajax发送fd参数时要告诉jQuery不要去处理发送的数据，
         不要去设置Content-Type请求头才可以发送成功，否则会报“Illegal invocation”的错误，
         也就是非法调用，所以要加上“processData: false,contentType: false,”
         * */


        function ReSizePic(ThisPic) {
            var RePicWidth = 200; //这里修改为您想显示的宽度值

            var TrueWidth = ThisPic.width; //图片实际宽度
            var TrueHeight = ThisPic.height; //图片实际高度

            if (TrueWidth > TrueHeight) {
                //宽大于高
                var reWidth = RePicWidth;
                ThisPic.width = reWidth;
                //垂直居中
                return TrueHeight * (reWidth / TrueWidth);  //将图片修改后的高度返回，供垂直居中用
            } else {
                //宽小于高
                ThisPic.height = RePicWidth;
            }
        }


    </script>
</head>
<body>

<div class="container" style="padding: 50px;font-size: 20px">
    <label>请选择要上传的图像文件：</label>
    <button id="select" class="btn btn-warning">重选</button>
    <button id="add" class="btn btn-primary">追加</button>
    <input type="file" name="fileList" id="file_input" multiple accept="image/*"/>
    <!--用input标签并选择type=file，记得带上multiple，不然就只能单选图片了-->
    <button id="submit" class="btn btn-success">提交</button>
    <div class="process-div">
        <h3>文件上传中，请稍等...</h3>
        <span class="container2">
                 <span id="progressBar" class="h-100P bar"></span>
             </span>
    </div>
</div>
</body>
</html>
